//
//  LoginViewController.m
//  cherryproduct
//
//  Created by Enter zhao on 14-8-6.
//  Copyright (c) 2014年 cherry. All rights reserved.
//

#import "LoginViewController.h"

#import "HttpNewBaseService.h"
#import "MemberCentreViewController.h"
#import "RegisterViewController.h"
#import "ForgetPwdViewController.h"

@interface LoginViewController ()

@end

@implementation LoginViewController

static NSMutableDictionary * userinfo;

+ (void)saveUserInfo
{
    NSString * str_id = [[LoginViewController shareUserInfo] objectForKey:@"id"];
    //[APService setTags:[NSSet setWithObjects:str_id, nil] alias:str_id callbackSelector:nil object:nil];
    [APService setAlias:str_id callbackSelector:nil object:nil];
    
    NSData * data = [NSKeyedArchiver archivedDataWithRootObject:[LoginViewController shareUserInfo]];
    [[NSUserDefaults standardUserDefaults] setObject:data forKey:kUserDefaultsInfo];
}

+ (NSMutableDictionary *)shareUserInfo
{
    if (userinfo==nil) {
        NSData * cookiesdata = [[NSUserDefaults standardUserDefaults] objectForKey:kUserDefaultsInfo];
        if ([cookiesdata length]) {
            NSDictionary * cookies = [NSKeyedUnarchiver unarchiveObjectWithData:cookiesdata];
            userinfo = [[NSMutableDictionary alloc] initWithDictionary:cookies copyItems:YES];
        } else {
            userinfo = [[NSMutableDictionary alloc] initWithCapacity:37];
            [userinfo setObject:@"0" forKey:KEY_HAVE_LOGIN];
        }
    }
    return userinfo;
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.myView.hidden = YES;
    UIButton * btn_left = (UIButton*)[self.navigationBar viewWithTag:1999];
    [btn_left setImage:[UIImage imageNamed:@"userback"] forState:UIControlStateNormal];
    [btn_left setImage:[UIImage imageNamed:@"userback"] forState:UIControlStateHighlighted];
    // Do any additional setup after loading the view from its nib.
    
    _userNameField.delegate = self;
    _passwordField.delegate = self;
    
    self.passwordField.SecureTextEntry=YES;
    self.passwordField.clearButtonMode=UITextFieldViewModeWhileEditing;
    self.userNameField.clearButtonMode=UITextFieldViewModeWhileEditing;
    
    self.userNameField.placeholder=@"请输入用户名";
    self.passwordField.placeholder=@"请输入密码";
    
    NSUserDefaults * defaults = [NSUserDefaults standardUserDefaults];
    NSString * username = [defaults objectForKey:@"USERNAME"];
    NSString * password = [defaults objectForKey:@"USERPASSWORD"];
    
    if (username && [username isKindOfClass:[NSString class]]) {
        self.userNameField.text=username;
    }
    
    if (password && [password isKindOfClass:[NSString class]]) {
        self.passwordField.text=password;
    }
    
    if ([TencentOAuth iphoneQQInstalled]) {
        self.btn_qq.hidden=NO;
    } else {
        self.btn_qq.hidden=YES;
    }

//    NSArray* array = [[NSArray alloc] initWithObjects:[self.view viewWithTag:11000],[self.view viewWithTag:11001], nil];
//    [UIView addAnimationArrayAndPlay:array delay:0.3f playType:PLAY_LIFT_RIGHT];
//    NSArray* array1 = [[NSArray alloc] initWithObjects:[self.view viewWithTag:11002], nil];
//    [UIView addAnimationArrayAndPlay:array1 delay:0.8f playType:PLAY_RIGHT_LIFT];
    
    
    [self.navigationBar setBackgroundColor:[UIColor clearColor]];

    _permissions = [NSMutableArray arrayWithObjects:
                     kOPEN_PERMISSION_GET_USER_INFO,
                     kOPEN_PERMISSION_GET_SIMPLE_USER_INFO,
                     kOPEN_PERMISSION_ADD_ALBUM,
                     kOPEN_PERMISSION_ADD_IDOL,
                     kOPEN_PERMISSION_ADD_ONE_BLOG,
                     kOPEN_PERMISSION_ADD_PIC_T,
                     kOPEN_PERMISSION_ADD_SHARE,
                     kOPEN_PERMISSION_ADD_TOPIC,
                     kOPEN_PERMISSION_CHECK_PAGE_FANS,
                     kOPEN_PERMISSION_DEL_IDOL,
                     kOPEN_PERMISSION_DEL_T,
                     kOPEN_PERMISSION_GET_FANSLIST,
                     kOPEN_PERMISSION_GET_IDOLLIST,
                     kOPEN_PERMISSION_GET_INFO,
                     kOPEN_PERMISSION_GET_OTHER_INFO,
                     kOPEN_PERMISSION_GET_REPOST_LIST,
                     kOPEN_PERMISSION_LIST_ALBUM,
                     kOPEN_PERMISSION_UPLOAD_PIC,
                     kOPEN_PERMISSION_GET_VIP_INFO,
                     kOPEN_PERMISSION_GET_VIP_RICH_INFO,
                     kOPEN_PERMISSION_GET_INTIMATE_FRIENDS_WEIBO,
                     kOPEN_PERMISSION_MATCH_NICK_TIPS_WEIBO,
                     nil];
    //_permissions = [[NSArray arrayWithObjects:@"get_user_info",@"get_simple_userinfo", @"add_t", nil] retain];
	
    NSString * appid = @"1102489759";
    
	_tencentOAuth = [[TencentOAuth alloc] initWithAppId:appid
											andDelegate:self];
    


}
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];


}
- (void)request:(WBHttpRequest *)request didFinishLoadingWithResult:(NSString *)result
{
    NSString *title = nil;
    UIAlertView *alert = nil;
    
    title = @"收到网络回调";
    alert = [[UIAlertView alloc] initWithTitle:title
                                       message:[NSString stringWithFormat:@"%@",result]
                                      delegate:nil
                             cancelButtonTitle:@"确定"
                             otherButtonTitles:nil];
    [alert show];
}

- (void)request:(WBHttpRequest *)request didFailWithError:(NSError *)error;
{
    NSString *title = nil;
    UIAlertView *alert = nil;
    
    title = @"请求异常";
    alert = [[UIAlertView alloc] initWithTitle:title
                                       message:[NSString stringWithFormat:@"%@",error]
                                      delegate:nil
                             cancelButtonTitle:@"确定"
                             otherButtonTitles:nil];
    [alert show];
}
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    NSTimeInterval animationDuration = 0.30f;
    [UIView beginAnimations:@"ResizeForKeyboard" context:nil];
    [UIView setAnimationDuration:animationDuration];
    CGRect rect = CGRectMake(0.0f,0 , self.view.frame.size.width, self.view.frame.size.height);
    self.view.frame = rect;
    [UIView commitAnimations];
    [_passwordField resignFirstResponder];
    [_userNameField resignFirstResponder];
    
}
-(BOOL)textFieldShouldReturn:(UITextField *)textField{
    
    
    NSTimeInterval animationDuration = 0.30f;
    [UIView beginAnimations:@"ResizeForKeyboard" context:nil];
    [UIView setAnimationDuration:animationDuration];
    CGRect rect = CGRectMake(0.0f,0 , self.view.frame.size.width, self.view.frame.size.height);
    self.view.frame = rect;
    [UIView commitAnimations];
    [textField resignFirstResponder];
    
    return YES;
    
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark -
#pragma mark qq联合登录
- (void)tencentDidLogin
{
    //_labelTitle.text = @"登录完成";
    if (_tencentOAuth.accessToken && 0 != [_tencentOAuth.accessToken length])
    {
        // 记录登录用户的OpenID、Token以及过期时间
        //_labelAccessToken.text = _tencentOAuth.accessToken;
        NSLog(@"qq登录成功,token:%@", _tencentOAuth.accessToken);
        NSLog(@"qq登录成功,openid:%@", _tencentOAuth.openId);
        //[_tencentOAuth accessToken] ;
        //[_tencentOAuth openId] ;
        //[_tencentOAuth expirationDate] ;
        
        //[_tencentOAuth setAccessToken:accessToken] ;
        //[_tencentOAuth setOpenId:openId] ;
        //[_tencentOAuth setExpirationDate:expirationDate] ;
        [self joinLoginQQ:nil];
    }
    else
    {
        //_labelAccessToken.text = @"登录不成功 没有获取accesstoken";
        NSLog(@"qq联合登录失败!");
        [self showAlertView:@"温馨提示" subtitle:@"登录失败"];
    }
}
-(void)tencentDidNotLogin:(BOOL)cancelled
{
    if (cancelled)
    {
        NSLog(@"qq用户取消登录!");
    }
    else
    {
        NSLog(@"qq登录失败!");
    }
}
-(void)tencentDidNotNetWork
{
    NSLog(@"无网络连接，请设置网络");
}

- (IBAction)qqbuttonAction:(UIButton *)sender {
    if ([TencentOAuth iphoneQQInstalled]) {
        [_tencentOAuth authorize:_permissions inSafari:NO];
    } else {
        //[self showAlertView:@"温馨提示" subtitle:@"请安装手机QQ!"];
    }
}

- (IBAction)sinaButtonAction:(UIButton *)sender {
    WBAuthorizeRequest * request = [WBAuthorizeRequest request];
    request.redirectURI = kRedirectURI;//http://sns.whalecloud.com/sina2/callback
    request.scope = @"all";
    request.userInfo = @{@"SSO_From": @"LoginViewController",
                         @"Other_Info_1": [NSNumber numberWithInt:123],
                         @"Other_Info_2": @[@"obj1", @"obj2"],
                         @"Other_Info_3": @{@"key1": @"obj1", @"key2": @"obj2"}};
    [WeiboSDK sendRequest:request];
}

- (IBAction)forgetPwdButtonAction:(UIButton *)sender {
    ForgetPwdViewController* vc = [[ForgetPwdViewController alloc] initWithNibName:@"ForgetPwdViewController" bundle:nil];
    [self.navigationController pushViewController:vc animated:YES];
}

- (IBAction)loginButtonAction:(UIButton *)sender {

    RegisterViewController* vc = [[RegisterViewController alloc] initWithNibName:@"RegisterViewController" bundle:nil];
    [self.navigationController pushViewController:vc animated:YES];
}

- (IBAction)enterButtonAction:(UIButton *)sender {
    if (_userNameField.text.length||_passwordField.text.length) {
        
        [self.view startLoadingAnimation];
//        进入个人中心
        NSMutableDictionary *requestDic = [[NSMutableDictionary alloc] initWithObjectsAndKeys:
                                           _userNameField.text, @"phone",_passwordField.text, @"pwd",nil];
        [[HttpNewBaseService sharedClient] postRequestOperation:@"member/login_phone" paramDictionary:requestDic onCompletion:^(NSString *responseString) {
            
            [self.view stopLoadingAnimation];

            @try {
                
                NSDictionary* dic = [responseString JSONValue];
                if ([[dic objectForKey:@"status"] intValue] == 1) {
                    {
                        //保存cookie
                        NSHTTPCookieStorage * cookieJar = [NSHTTPCookieStorage sharedHTTPCookieStorage];
                        NSData *data = [NSKeyedArchiver archivedDataWithRootObject:[cookieJar cookies]];
                        [[NSUserDefaults standardUserDefaults] setObject:data forKey:kUserDefaultsCookie];
                    }
                    //登陆成功
                    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
                    [defaults setObject:_userNameField.text forKey:@"USERNAME"];
                    [defaults setObject:_passwordField.text forKey:@"USERPASSWORD"];
                    [defaults synchronize];
                    
                    {
                        NSDictionary * data_dic = [dic objectForKey:@"data"];
                        [[LoginViewController shareUserInfo] setDictionary:data_dic];
                        [[LoginViewController shareUserInfo] setObject:@"1" forKey:KEY_HAVE_LOGIN];
                        
                        {
                            NSString * logo = [data_dic objectForKey:@"logo"];
                            if (logo) {
                                NSString * new_logo = [NSString stringWithFormat:@"%@%@",JPG,logo];
                                //保存login img
                                [[LoginViewController shareUserInfo] setObject:new_logo forKey:@"new_logo"];
                            }
                            NSString * cover = [data_dic objectForKey:@"cover"];
                            if (cover) {
                                NSString * pp = [cover stringByReplacingOccurrencesOfString:@"Attachment/" withString:@""];
                                NSString * new_cover = [NSString stringWithFormat:@"%@%@",JPG,pp];
                                //保存login img
                                [[LoginViewController shareUserInfo] setObject:new_cover forKey:@"new_cover"];
                            }
                        }
                        [LoginViewController saveUserInfo];
                    }
                    if (self.m_is_come_other) {
                        //[self showAlertView:@"温馨提示" subtitle:@"登录成功!"];
                        if (self.block_dismiss) {
                            self.block_dismiss(0);
                        }
                        [self.navigationController popViewControllerAnimated:NO];
                    } else {
                        MemberCentreViewController* vc = [[MemberCentreViewController alloc] init];
                        [self.navigationController pushViewController:vc animated:YES];
                    }
                }
                else
                {
                    [self showAlertView:@"温馨提示" subtitle:[dic objectForKey:@"message"]];
                }
            }
            @catch (NSException *exception) {
                [self showAlertView:@"温馨提示" subtitle:@"网络通讯失败！"];
            }
            @finally {
                ;
            }
            
        } onError:^(NSError *error) {
            [self.view stopLoadingAnimation];
            [self showAlertView:@"温馨提示" subtitle:@"网络断了！"];
        } onAnimated:YES];
    }
    else
    {
        [self showAlertView:@"温馨提示" subtitle:@"用户名密码不能为空~"];
    }
}

#pragma mark -
#pragma mark JoinLogin
- (void)joinLoginWeibo:(WBBaseResponse *)response;
{
    //NSDictionary * dic = response.userInfo;
    //NSLog(@"name:%@", [[dic objectForKey:@"app"] objectForKey:@"name"]);
    if ([(WBAuthorizeResponse *)response userID] == nil||
        [(WBAuthorizeResponse *)response accessToken] == nil) {
        //[self showAlertView:@"温馨提示" subtitle:@"登录失败!"];
        return;
    }
    
    NSMutableDictionary * requestDic = [[NSMutableDictionary alloc] initWithObjectsAndKeys:
                                        [(WBAuthorizeResponse *)response userID], @"openid",
                                        [(WBAuthorizeResponse *)response accessToken], @"access_token",
                                        @"3", @"type",//3weibo
                                        //[dic objectForKey:@"name"], @"name",
                                        nil];
    
    [self.view startLoadingAnimation];
    [[HttpNewBaseService sharedClient] postRequestOperation:@"member/open_auth"
                                            paramDictionary:requestDic
                                               onCompletion:^(NSString *responseString)
    {
        [self.view stopLoadingAnimation];
        
        @try {
            
            NSDictionary* dic = [responseString JSONValue];
            if ([[dic objectForKey:@"status"] intValue] == 1) {
                {
                    //保存cookie
                    NSHTTPCookieStorage * cookieJar = [NSHTTPCookieStorage sharedHTTPCookieStorage];
                    NSData * data = [NSKeyedArchiver archivedDataWithRootObject:[cookieJar cookies]];
                    [[NSUserDefaults standardUserDefaults] setObject:data forKey:kUserDefaultsCookie];
                }
                //登陆成功
                /*
                NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
                [defaults setObject:_userNameField.text forKey:@"USERNAME"];
                [defaults setObject:_passwordField.text forKey:@"USERPASSWORD"];
                [defaults synchronize];*/
                
                {
                    NSDictionary * data_dic = [dic objectForKey:@"data"];
                    [[LoginViewController shareUserInfo] setDictionary:data_dic];
                    [[LoginViewController shareUserInfo] setObject:@"1" forKey:KEY_HAVE_LOGIN];
                    
                    {
                        NSString * logo = [data_dic objectForKey:@"logo"];
                        if (logo) {
                            NSString * new_logo = [NSString stringWithFormat:@"%@%@",JPG,logo];
                            //保存login img
                            [[LoginViewController shareUserInfo] setObject:new_logo forKey:@"new_logo"];
                        }
                        NSString * cover = [data_dic objectForKey:@"cover"];
                        if (cover) {
                            NSString * pp = [cover stringByReplacingOccurrencesOfString:@"Attachment/" withString:@""];
                            NSString * new_cover = [NSString stringWithFormat:@"%@%@",JPG,pp];
                            //保存login img
                            [[LoginViewController shareUserInfo] setObject:new_cover forKey:@"new_cover"];
                        }
                    }
                    [LoginViewController saveUserInfo];
                }
                if (self.m_is_come_other) {
                    //[self showAlertView:@"温馨提示" subtitle:@"登录成功!"];
                    if (self.block_dismiss) {
                        self.block_dismiss(0);
                    }
                    [self.navigationController popViewControllerAnimated:NO];
                } else {
                    MemberCentreViewController* vc = [[MemberCentreViewController alloc] init];
                    [self.navigationController pushViewController:vc animated:YES];
                }
            }
            else
            {
                [self showAlertView:@"温馨提示" subtitle:[dic objectForKey:@"message"]];
            }
        } @catch (NSException *exception) {
            [self showAlertView:@"温馨提示" subtitle:@"网络通讯失败！"];
        }
    } onError:^(NSError *error) {
        [self.view stopLoadingAnimation];
        [self showAlertView:@"温馨提示" subtitle:@"网络断了！"];
    } onAnimated:YES];
}

- (void)joinLoginQQ:(NSDictionary*)dic;
{
    NSLog(@"qq登录成功,token:%@", _tencentOAuth.accessToken);
    NSLog(@"qq登录成功,openid:%@", _tencentOAuth.openId);
    
    NSMutableDictionary * requestDic = [[NSMutableDictionary alloc] initWithObjectsAndKeys:
                                        _tencentOAuth.openId, @"openid",
                                        _tencentOAuth.accessToken, @"access_token",
                                        @"1", @"type",//1:qq
                                        //[dic objectForKey:@"name"], @"name",
                                        nil];
    
    [self.view startLoadingAnimation];
    
    [[HttpNewBaseService sharedClient] postRequestOperation:@"member/open_auth"
                                            paramDictionary:requestDic
                                               onCompletion:^(NSString *responseString)
     {
         [self.view stopLoadingAnimation];
         
         @try {
             
             NSDictionary* dic = [responseString JSONValue];
             if ([[dic objectForKey:@"status"] intValue] == 1) {
                 {
                     //保存cookie
                     NSHTTPCookieStorage * cookieJar = [NSHTTPCookieStorage sharedHTTPCookieStorage];
                     NSData * data = [NSKeyedArchiver archivedDataWithRootObject:[cookieJar cookies]];
                     [[NSUserDefaults standardUserDefaults] setObject:data forKey:kUserDefaultsCookie];
                 }
                 //登陆成功
                 /*
                  NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
                  [defaults setObject:_userNameField.text forKey:@"USERNAME"];
                  [defaults setObject:_passwordField.text forKey:@"USERPASSWORD"];
                  [defaults synchronize];*/
                 
                 {
                     NSDictionary * data_dic = [dic objectForKey:@"data"];
                     [[LoginViewController shareUserInfo] setDictionary:data_dic];
                     [[LoginViewController shareUserInfo] setObject:@"1" forKey:KEY_HAVE_LOGIN];
                     
                     {
                         NSString * logo = [data_dic objectForKey:@"logo"];
                         if (logo) {
                             NSString * new_logo = [NSString stringWithFormat:@"%@%@",JPG,logo];
                             //保存login img
                             [[LoginViewController shareUserInfo] setObject:new_logo forKey:@"new_logo"];
                         }
                         NSString * cover = [data_dic objectForKey:@"cover"];
                         if (cover) {
                             NSString * pp = [cover stringByReplacingOccurrencesOfString:@"Attachment/" withString:@""];
                             NSString * new_cover = [NSString stringWithFormat:@"%@%@",JPG,pp];
                             //保存login img
                             [[LoginViewController shareUserInfo] setObject:new_cover forKey:@"new_cover"];
                         }
                     }
                     [LoginViewController saveUserInfo];
                 }
                 if (self.m_is_come_other) {
                     //[self showAlertView:@"温馨提示" subtitle:@"登录成功!"];
                     if (self.block_dismiss) {
                         self.block_dismiss(0);
                     }
                     [self.navigationController popViewControllerAnimated:NO];
                 } else {
                     MemberCentreViewController* vc = [[MemberCentreViewController alloc] init];
                     [self.navigationController pushViewController:vc animated:YES];
                 }
             }
             else
             {
                 [self showAlertView:@"温馨提示" subtitle:[dic objectForKey:@"message"]];
             }
         } @catch (NSException *exception) {
             [self showAlertView:@"温馨提示" subtitle:@"网络通讯失败！"];
         }
     } onError:^(NSError *error) {
         [self.view stopLoadingAnimation];
         [self showAlertView:@"温馨提示" subtitle:@"网络断了！"];
     } onAnimated:YES];
}

@end
















